-- CJson install
cjson = require("cjson")
cjson2 = cjson.new()
cjson_safe = require("cjson.safe")
room = require("chatroom")
md5 = require("md5")
protocol = require("cs_protocol")

TEST_AGENT_KEY="987654321"
TEST_CLIENT_KEY="123456789"

-- condition functions
function condi_only_others(args, user)
	return user.Uid ~= args.Uid
end

function init()
	print("init lua")
	common.dumplog("init ok")
	common.warnlog("test version")
end

function broadcast(condition, msgId, msg)
	local func = function(user, arg)
		if user ~= nil and (condition == nil or condition.func(condition.args, user)) then
			networking.request(user.Uid, msgId, msg)
		end
	end
	room.foreach(func, nil)
end

-- c funstions
function received_packet(jsonargs)
	common.dumplog("received_packet(" .. jsonargs .. ")")
	return true
end

function client_login(jsonargs)
	common.dumplog("client_login(" .. jsonargs .. ")")
	args = cjson.decode(jsonargs)
	local uid = args.Uid
	local rid = args.Rid
	local timestamp = args.Timestamp
	local sign = args.Sign
	local b = false
	local checkSign
	b,checkSign = md5.sumhexa(uid .. rid .. timestamp .. TEST_CLIENT_KEY)
	if b and checkSign == sign then
		-- sign pass
		common.dumplog("client sign check pass")
		logical.connection_auth_pass(uid, args._connectionId)
		return true
	else
		common.warnlog("client sign check failed")
		return false
	end
end

function new_user(jsonargs)
	common.dumplog("new_user(" .. jsonargs .. ")")
	args = cjson.decode(jsonargs)
--	args._connectionId = connectionId
	if args._reconnected == 0 then
		common.dumplog("addUser(" .. args.Uid .. ")")
		room.add(args)
		broadcast({func=condi_only_others, args=args}, 202, "{Mid=1,Uid=" .. args.Uid .. "}") 
	else
		common.dumplog("updateUser(" .. args.Uid .. ")")
		room.update(args)
	end
	room.dump()
end

function delete_user(jsonargs)
	common.dumplog("delete_user(" .. jsonargs .. ")")
	args = cjson.decode(jsonargs)
	room.delete(args)
	broadcast({func=condi_only_others, args=args}, 202, "{Mid=2,Uid=" .. args.Uid .. "}") 
	room.dump()
end

function proxy_to_client(args)
	-- common.dumplog("args: " .. args)
end

init()